package com.dsunsoft.rtu.core;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * RabbitMqProvider
 */
@Slf4j
@Component
public class RabbitMqProvider {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发货消息(direct exchange)
     *
     * @param queueKey 队列名称
     * @param message  发送的消息
     * @throws AmqpException ex
     */
    public void send(String queueKey, Object message) throws AmqpException {
        try {
            rabbitTemplate.convertAndSend(queueKey, message);
        } catch (Exception e) {
            log.error("send error: ", e);
            throw e;
        }
    }

    /**
     * 发货消息(topic exchange)
     *
     * @param exchange   topic exchange 名称
     * @param routingKey 路由匹配,* 匹配零个或一个单词,# 匹配任意个单词
     * @param message    发送的消息
     * @throws AmqpException ex
     */
    public void send(String exchange, String routingKey, Object message) throws AmqpException {
        try {
            rabbitTemplate.convertAndSend(exchange, routingKey, message);
        } catch (Exception e) {
            log.error("send error: ", e);
            throw e;
        }
    }

    /**
     * 转换并发送消息,且等待消息者返回响应消息(direct exchange)
     *
     * @param queueKey 队列名称
     * @param message  发送的消息
     * @param <T>      返回类型
     * @return 返回值
     * @throws AmqpException ex
     */
    @SuppressWarnings("unchecked")
    public <T> T sendAndReceive(String queueKey, Object message) throws AmqpException {
        try {
            return (T) rabbitTemplate.convertSendAndReceive(queueKey, message);
        } catch (Exception e) {
            log.error("sendAndReceive error: ", e);
            throw e;
        }
    }

    /**
     * 转换并发送消息,且等待消息者返回响应消息(topic exchange)
     *
     * @param exchange   topic exchange 名称
     * @param routingKey 路由匹配,* 匹配零个或一个单词,# 匹配任意个单词
     * @param message    发送的消息
     * @param <T>        返回类型
     * @return 返回值
     * @throws AmqpException ex
     */
    @SuppressWarnings("unchecked")
    public <T> T sendAndReceive(String exchange, String routingKey, Object message) throws AmqpException {
        try {
            return (T) rabbitTemplate.convertSendAndReceive(exchange, routingKey, message);
        } catch (Exception e) {
            log.error("sendAndReceive error: ", e);
            throw e;
        }
    }
}
